<?php

namespace app\kefu\controller;
use think\Controller;
class Admin extends Controller
{
  
    public function index()
    {
       $kf_id=I('get.id');
       $kefu=M('service')->where('id',$kf_id)->find();

       // 查询客服信息
       $kefuinfo=M('service')->where('admin_id',$kefu['admin_id'])->select();

       foreach ($kefuinfo as $key => $value) {
         $kefu_info[$value['kf_no']]=$value;
       }
       if(IS_AJAX){
          $type=I('get.type');
          if($type=="get_chat_list"){
            //查询历史聊天记录
           $user_id=I('get.user_id');
           $p=(int)I('get.p');
           $user=M('users')->field('head_pic,nickname,user_id')->where('user_id',$user_id)->find();
           $user['nickname']=base64_decode($user['nickname']);
           
           $pcount=10;
           $total_count=M('service_log')->where('from_uid='.$user_id.' or to_uid='.$user_id)->count();
           $page=ceil($total_count/$pcount);
           if($p==-1){
           	$p=$page;
           }
           $start=($p-1)*$pcount;
           
           $chatlist=M('service_log')->where('from_uid='.$user_id.' or to_uid='.$user_id)->limit($start,$pcount)->order('id asc')->select();
            rsort($chatlist);
            $result['page']=$p;
            $result['total_page']=$page;
            $result['chatlist']=$chatlist;
            $result['users']=$user;
            echo json_encode($result);
          }
        
                
          exit;
       }else{
         $chatusers=M('service_log t0')->field('t0.*,t1.nickname,t1.head_pic')->join('tp_users t1','t0.from_uid=t1.user_id','left')->where('t0.to_uid',$kefu['kf_no'])->group('t0.from_uid')->order('t0.id desc')->select();
         $this->assign('chatusers',$chatusers);
       }

       $this->assign('user',$user);
       $this->assign('page',$page);
       $this->assign('kefuinfo',json_encode($kefu_info));
       $this->assign('kefu',$kefu);
       return $this->fetch();
    }

}